<?php

namespace App\Http\Controllers\Backend\Product;

 
use App\ConstDir\ErrorConst;
use App\Http\Controllers\Backend\BaseController;
use App\Repository\Repositories\Interfaces\AttributeValuesRepository;
use Illuminate\Http\Request;
 
 
class AttributeValueController extends BaseController
{
    
    protected $attribute_value_repo;
    
    public function __construct(AttributeValuesRepository $attribute_value_repo)
    {
        $this->attribute_value_repo = $attribute_value_repo;
        
//         $this->attribute_value_repo->scopeQuery(function ($query) {
//             return $query->where(['is_common'=>1]);
//         });
        
    }
    
    public function index(Request $request)
    {
        $perPage = $request->input("perPage",$this->perPage);
        $attrs = $this->attribute_value_repo->with(['attribute'])->paginate($perPage);
        
        return $this->success(ErrorConst::SUCCESS_CODE, $attrs,true);
    }
    
    public function show($id)
    {
        $attr = $this->attribute_value_repo->find($id);
        return $this->success(ErrorConst::SUCCESS_CODE, $attr);
    }
    
    public function create(Request $request)
    {
        
        $this->validate($request,[
            'value'=> 'required|string',
            'attribute_id'=> 'required|integer|exists:attributes,id',
            'sort'=>'integer',
        ]);
        
        $data = $request->all();
        
        $value_arr = explode(",",$data['value']);
        unset($data['value']);
        $attr = false;
        foreach($value_arr as $v){
            if($v){
                $data['value'] = $v;
                $attr = $this->attribute_value_repo->create($data);
            }
           
        }
        
        if($attr){
            return $this->success(ErrorConst::SUCCESS_CODE, $attr['data']);
        }else{
            return $this->error(ErrorConst::FAILED_CODE);
        }
        
    }
    
    public function update(Request $request, $id)
    {
        $this->validate($request,[
            'value'=> 'string',
            'attribute_id'=> 'integer|exists:attributes,id',
            'sort'=>'integer',
        ]);
        $data = $request->all();
        
        $ret = $this->attribute_value_repo->update($data, $id);
        if($ret){
            return $this->success(ErrorConst::SUCCESS_CODE, ErrorConst::SUCCESS_CODE_MSG);
        }else{
            return $this->error(ErrorConst::FAILED_CODE);
        }
    }
    
    public function delete($id)
    {
        $ret = $this->attribute_value_repo->delete($id);
        
        
        if ($ret) {
            return $this->success('删除成功');
        } else {
            return $this->error('删除失败');
        }
    }
   
}
